﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Collections;
using AmiEmuLib.AmigaConfiguration;
using System.Diagnostics;
using TomanuExtensions;

namespace AmiEmuLib.Configuration.DefaultAmigaConfigsConfig
{
    /// <summary>
    /// List of default amiga configurations. Loaded from xmls.
    /// </summary>
    [DebuggerDisplay("Count = {Count}")]
    public static class DefaultAmigaConfigs
    {
        /// <summary>
        /// List of default configs.
        /// </summary>
        private static List<DefaultAmigaConfig> m_configs = new List<DefaultAmigaConfig>();

        /// <summary>
        /// Static constructor.
        /// </summary>
        static DefaultAmigaConfigs()
        {
            using (Stream stream = StreamExtensions.FromResource(typeof(DefaultAmigaConfigs), 
                "DefaultAmigaConfigs.xml"))
            {
                XmlReaderExtensions.ReadXml(stream, (reader) =>
                {
                    reader.ReadStartElement(typeof(DefaultAmigaConfigs).Name);

                    while (reader.IsStartElement())
                        m_configs.Add(new DefaultAmigaConfig(reader));

                    reader.ReadEndElement();
                });
            }
        }

        /// <summary>
        /// Developer only.
        /// </summary>
        public static void SaveToXml()
        {
            XmlWriterExtensions.WriteXml(
                @"..\..\..\amiemu_lib\Configuration\DefaultAmigaConfigsConfig\DefaultAmigaConfigs1.xml", (writer) =>
            {
                writer.WriteStartElement(typeof(DefaultAmigaConfigs).Name);

                foreach (var def_config in m_configs)
                    def_config.WriteXml(writer);

                writer.WriteEndElement();
            });
        }

        public static IEnumerable<DefaultAmigaConfig> GetConfigs(AmigaModel a_amiga_model)
        {
            return from dac in m_configs
                   where dac.AmigaModel == a_amiga_model
                   select dac;
        }

        /// <summary>
        /// List of default configs.
        /// </summary>
        public static IEnumerable<DefaultAmigaConfig> Configs
        {
            get
            {
                return m_configs;
            }
        }

        /// <summary>
        /// First default config.
        /// </summary>
        /// <param name="amigaModel"></param>
        public static AmigaConfig GetConfig(AmigaModel a_amiga_model)
        {
            return GetConfigs(a_amiga_model).First().GetConfigCopy();
        }
    }
}
